package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.StatementData;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.IFinanceService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ResultCode;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class FinanceServiceImpl implements IFinanceService {

    @Autowired
    OrderApplyMapper orderApplyMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    CoursePricingMapper coursePricingMapper;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    RecordCostMapper recordCostMapper;

    @Autowired
    IQuarterService iQuarterService;



    @Override
    public IPage<StatementData> statementData(IPage<?> page,String schoolId, String startDate,String endDate, String subjectsId,String studentName,String yearPart,String quarterNum,String lessonType,String type) {
        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer history = 0;
        if (quarterNow.getYearPart().equals(Integer.parseInt(yearPart)) && quarterNow.getNum().equals(Integer.parseInt(quarterNum))) {
        }else {
            history = 1;
        }


        Integer type1 = 0;
        if(StringUtils.isNotBlank(type)){
            type1 = Integer.valueOf(type);
        }

        IPage<StatementData> statementDataIPage =  orderDetailMapper.statementData(page,schoolId,subjectsId,studentName,yearPart,quarterNum,lessonType,history, type1,startDate,endDate);


        for (StatementData statementData:statementDataIPage.getRecords()){
            /*Student student = studentMapper.selectById(statementData.getStudentId());
            if(student != null){
                statementData.setStudentName(student.getName());
            }
            Grade grade = gradeMapper.selectById(statementData.getGradeId());
            if(grade !=null){
                statementData.setGradeId(grade.getId());
            }*/
            if (statementData.getYearClassId() != null){
                statementData.setYearClassId(statementData.getYearClassId());
                statementData.setYearClassName(CommonUtil.getYearClassNameForId(statementData.getYearClassId()));
            }

            //退费金额,备注（2023-07-31,取消从退费里面计算）
            /*QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
            orderApplyQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"b.school_id",schoolId);
            orderApplyQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"b.subjects_id",subjectsId);
            if(yearAndQuarter.equals(0)){
                orderApplyQueryWrapper.eq("b.year_and_quarter",0);
            }else {
                orderApplyQueryWrapper.ge("b.year_and_quarter",yearAndQuarter);
            }

            //orderApplyQueryWrapper.eq("b.deleted",0);
            orderApplyQueryWrapper.ne("a.status",2);
            orderApplyQueryWrapper.eq("a.order_type",4);
            orderApplyQueryWrapper.eq("b.deleted",0);
            orderApplyQueryWrapper.eq("b.student_id",statementData.getStudentId());
            BigDecimal outPrice = statementData.getOutPrice();
            if (isUserQuarterDate == false){
                outPrice = orderDetailMapper.getStudentOutPrice(orderApplyQueryWrapper);
                statementData.setOutPrice(outPrice);
            }*/


            //实际使用课时，与金额
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
            recordCourseQueryWrapper.eq("year_part",yearPart);
            recordCourseQueryWrapper.eq("quarter",quarterNum);
            recordCourseQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
                recordCourseQueryWrapper.between("school_date",startDate,endDate);
            }
            recordCourseQueryWrapper.eq("is_deduct_house",1);
            recordCourseQueryWrapper.eq("is_deduct_money",1);
            recordCourseQueryWrapper.eq("student_id",statementData.getStudentId());
            recordCourseQueryWrapper.eq("deleted",0);
            /*Integer useCourseCount = recordCourseMapper.getUseCourseCount(recordCourseQueryWrapper);
            statementData.setUseCourseCount(useCourseCount);

            BigDecimal realityPirce = recordCourseMapper.getRealityPirce(recordCourseQueryWrapper);
            statementData.setRealityPirce(realityPirce);*/
            /*Integer useCourseCount = statementData.getUseCourseCount();

            if (isUserQuarterDate == false){
                Map<String,BigDecimal> mapMoney = recordCourseMapper.getRealityPirceAndRealityPirce(recordCourseQueryWrapper);
                useCourseCount = Integer.parseInt(mapMoney.get("buckleClassHouse").toString());
                statementData.setUseCourseCount(useCourseCount);
                BigDecimal realityPirce = mapMoney.get("buckleClassMoney");
                if (isAddAdvancePrice){
                    realityPirce = realityPirce.add(statementData.getAbnormalPrice());//添加异常收入
                }
                statementData.setRealityPirce(realityPirce);//实际收入
            }*/

            /*备注（2023-07-31,取消从退费里面计算）
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            studentGradeQueryWrapper.eq("student_id",statementData.getStudentId());
            studentGradeQueryWrapper.eq("year_part",quarter.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num",quarter.getNum());
            studentGradeQueryWrapper.ne("status",3);

            Integer useCourseCount = recordCourseMapper.getUseCourseCountForGrade(studentGradeQueryWrapper);
            statementData.setUseCourseCount(useCourseCount);*/
            /*if (isUserQuarterDate == false){
                //预收款
                BigDecimal advancePrice = statementData.getSolidPrice().subtract(outPrice).subtract(statementData.getRealityPirce());
                statementData.setAdvancePrice(advancePrice);
            }else {
                statementData.setAdvancePrice(statementData.getResiduePrice());
            }*/

            statementData.setAdvancePrice(statementData.getResiduePrice());

            //到课课时（实际使用课时）（2023-07-31,取消从退费里面计算）
            //recordCourseQueryWrapper.eq("is_deduct_money",1);
            //Integer arriveCourseCount = recordCourseMapper.getUseCourseCount(recordCourseQueryWrapper);


            /**
             * 请假课次
             */
            recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
            recordCourseQueryWrapper.eq("year_part",yearPart);
            recordCourseQueryWrapper.eq("quarter",quarterNum);
            recordCourseQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
                recordCourseQueryWrapper.between("school_date",startDate,endDate);
            }
            recordCourseQueryWrapper.eq("is_deduct_house",1);
            recordCourseQueryWrapper.ne("is_repair",1);//不等于已补课的
            recordCourseQueryWrapper.ne("status",1);//不等于1
            recordCourseQueryWrapper.eq("student_id",statementData.getStudentId());
            recordCourseQueryWrapper.eq("deleted",0);
            Integer leaveCourseCount = recordCourseMapper.getLeaveCourseCount(recordCourseQueryWrapper);
            statementData.setLeaveCourseCount(leaveCourseCount);


            //statementData.setRealityPirce(statementData.getSolidPrice().subtract(statementData.getOutPrice()).subtract(statementData.getAdvancePrice()));
            //statementData.setRealityPirce(statementData.getSolidPrice());
            //System.out.println("statementData:"+statementData.toString());
            //System.out.println();
        }

        return statementDataIPage;
    }

    @Override
    @Transactional
    public boolean updatePrice(String schoolId,String studentId, String subjectsId, BigDecimal beforePrice,BigDecimal afterPrice,Quarter quarter,Integer lessonType) {
        Integer yearAndQuarter = 0;
        if(quarter != null){
            //throw new CommonException(ResultCode.quarterNo);
            yearAndQuarter = Integer.parseInt(quarter.getYearPart()+""+quarter.getNum());
        }
        BigDecimal residuePrice = orderDetailMapper.getAllResiduePrice(Long.parseLong(schoolId),Long.parseLong(studentId),Long.parseLong(subjectsId),yearAndQuarter,lessonType);
        int compareResult = afterPrice.compareTo(beforePrice);
        if (compareResult == 0){
            return true;
        }

        BigDecimal subPrice = afterPrice.subtract(beforePrice);//修改后相差金额

        OrderDetail orderDetail = this.getAtorderDetailOne(schoolId,studentId,subjectsId,quarter,1,lessonType);
        if (orderDetail == null){
            return  false;
        }
        BigDecimal diffPrice = subPrice;//差额
        CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
        //本次扣多少个课时
        BigDecimal stuDeductHour =   new BigDecimal(3);
        //学生一次使用课时使用金额
        BigDecimal houseClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3),BigDecimal.ROUND_HALF_UP));

        /**
         * 金额调整变大
         */
        if (compareResult > 0){
            Integer i = 1;
            //获取所扣金额小于一节课的钱的数据
            List<RecordCourse> recordCourseList = this.getLessBuckleClassHouseList(schoolId,studentId,subjectsId,quarter,houseClassMoney);

            for (RecordCourse recordCourse:recordCourseList){
                //如果还存在有多出的金额
                if (diffPrice.compareTo(BigDecimal.ZERO)>0){
                    //本次减掉金额
                    BigDecimal recordCourseDiffPrice =  houseClassMoney.subtract(recordCourse.getBuckleClassMoney());//应该加上多少钱
                    if (diffPrice.compareTo(recordCourseDiffPrice)<0){
                        recordCourseDiffPrice = diffPrice;
                    }else {
                        //如果是最后一条数据,并没有了剩余课时，全部减掉
                        if (recordCourseList.size() == i){
                            //如果没有剩余课时
                            if (orderDetail.getResidueCourseCount() == 0){
                                recordCourseDiffPrice = diffPrice;
                            }
                        }
                    }
                    diffPrice = diffPrice.subtract(recordCourseDiffPrice);
                    recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(recordCourseDiffPrice));
                    recordCourseMapper.updateById(recordCourse);
                    RecordCost recordCost = recordCostMapper.selectById(recordCourse.getId());
                    OrderDetail orderDetailOld = null;
                    if (recordCost != null){
                        recordCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
                        recordCostMapper.updateById(recordCost);
                        orderDetailOld = orderDetailMapper.selectById(recordCost.getOrderDetailId());
                    }
                    this.addApplyPrice(orderDetail,orderDetailOld,recordCourseDiffPrice,true);
                }
                i++;
            }

            //剩下的加到订单里
            if (diffPrice.compareTo(BigDecimal.ZERO)>0){
                diffPrice = this.addOrderDetailPrice(schoolId,studentId,subjectsId,quarter,diffPrice,houseClassMoney);
                if (diffPrice.compareTo(BigDecimal.ZERO)>0){
                    orderDetail = this.getAtorderDetailOne(schoolId,studentId,subjectsId,quarter,1,lessonType);
                    if (orderDetail.getResidueCourseCount()>0){
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(diffPrice));
                    }
                    orderDetailMapper.updateById(orderDetail);
                    this.addApplyPrice(orderDetail,null,diffPrice,false);
                }
            }
            return true;
        }else if (compareResult<0){//金额调整变小

            if (diffPrice.compareTo(BigDecimal.ZERO)<0){

                //获取所扣金额大于一节课的钱的数据
                List<RecordCourse> recordCourseListBig = this.getBigBuckleClassHouseList(schoolId,studentId,subjectsId,quarter,houseClassMoney);

                for (RecordCourse recordCourse:recordCourseListBig){
                    if (recordCourse.getBuckleClassMoney().compareTo(BigDecimal.ZERO) == 0){
                        continue;
                    }
                    //如果还存在有少出的金额
                    if (diffPrice.compareTo(BigDecimal.ZERO)<0){
                        //本次减掉金额
                        BigDecimal recordCourseDiffPrice =  recordCourse.getBuckleClassMoney().subtract(houseClassMoney);//应该减多少钱
                        if (diffPrice.add(recordCourseDiffPrice).compareTo(BigDecimal.ZERO)>0){
                            recordCourseDiffPrice = diffPrice.negate();//转正数
                        }
                        diffPrice = diffPrice.add(recordCourseDiffPrice);//因为diffPrice是负数所以这里用加号

                        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().subtract(recordCourseDiffPrice));
                        recordCourseMapper.updateById(recordCourse);
                        RecordCost recordCost = recordCostMapper.selectById(recordCourse.getId());
                        OrderDetail orderDetailOld = null;
                        if (recordCost != null){
                            recordCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
                            recordCostMapper.updateById(recordCost);
                            orderDetailOld = orderDetailMapper.selectById(recordCost.getOrderDetailId());
                        }
                        this.subApplyPrice(orderDetail,orderDetailOld,recordCourseDiffPrice,true);
                    }
                }
            }

            //获取订单里还有剩余课时和金额的
            List<OrderDetail> orderDetailList = this.getHasResiduePriceList(schoolId,studentId,subjectsId,quarter,1);
            for (OrderDetail orderDetailItem:orderDetailList){
                //如果还存在有少出的金额
                if (diffPrice.compareTo(BigDecimal.ZERO)<0){
                    //本次减掉金额
                    BigDecimal recordCourseDiffPrice =  orderDetailItem.getResiduePrice();//应该减多少钱
                    if (diffPrice.add(recordCourseDiffPrice).compareTo(BigDecimal.ZERO)>0){
                        recordCourseDiffPrice = diffPrice.negate();//转正数
                    }
                    diffPrice = diffPrice.add(recordCourseDiffPrice);
                    orderDetailItem.setResiduePrice(orderDetailItem.getResiduePrice().subtract(recordCourseDiffPrice));
                    orderDetailMapper.updateById(orderDetailItem);

                    this.subApplyPrice(orderDetailItem,null,recordCourseDiffPrice,false);
                }
            }


            if (diffPrice.compareTo(BigDecimal.ZERO)<0){
                //获取已扣金额的数据
                List<RecordCourse> deductRecordCourseList = this.getDeductList(schoolId,studentId,subjectsId,quarter);
                for (RecordCourse recordCourse:deductRecordCourseList){
                    if (recordCourse.getBuckleClassMoney().compareTo(BigDecimal.ZERO) == 0){
                        continue;
                    }
                    //如果还存在有少出的金额
                    if (diffPrice.compareTo(BigDecimal.ZERO)<0){
                        //本次减掉金额
                        BigDecimal recordCourseDiffPrice =  recordCourse.getBuckleClassMoney();//应该减多少钱
                        if (diffPrice.add(recordCourseDiffPrice).compareTo(BigDecimal.ZERO)>0){
                            recordCourseDiffPrice = diffPrice.negate();//转正数
                        }
                        diffPrice = diffPrice.add(recordCourseDiffPrice);

                        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().subtract(recordCourseDiffPrice));
                        recordCourseMapper.updateById(recordCourse);
                        RecordCost recordCost = recordCostMapper.selectById(recordCourse.getId());
                        OrderDetail orderDetailOld = null;
                        if (recordCost != null){
                            recordCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
                            recordCostMapper.updateById(recordCost);
                            orderDetailOld = orderDetailMapper.selectById(recordCost.getOrderDetailId());
                        }
                        this.subApplyPrice(orderDetail,orderDetailOld,recordCourseDiffPrice,true);
                    }
                }
            }

            //剩下的减少
            if (diffPrice.compareTo(BigDecimal.ZERO)<0){
                this.subApplyPrice(orderDetail,null,diffPrice.negate(),false);
            }
        }
        return true;
    }

    @Override
    public IPage<StatementData> statementDataStill(IPage<?> page, String schoolId, String startDate, String endDate, String subjectsId, String studentName, String yearPart,String quarterNum, String lessonType, String type) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        Integer history = 0;
        if (quarterNow.getYearPart().equals(Integer.parseInt(yearPart)) && quarterNow.getNum().equals(Integer.parseInt(quarterNum))) {

        }else {
            history = 1;
        }

        IPage<StatementData> statementDataIPage =  orderDetailMapper.statementDataStill(page,schoolId,subjectsId,studentName,yearPart,quarterNum,lessonType,history,startDate,endDate);

        for (StatementData statementData:statementDataIPage.getRecords()){
            if (statementData.getYearClassId() != null){
                statementData.setYearClassName(CommonUtil.getYearClassNameForId(statementData.getYearClassId()));
            }
            statementData.setAdvancePrice(statementData.getResiduePrice());
        }

        return statementDataIPage;
    }

    @Override
    public IPage<StatementData> statementDataEnd(IPage<?> page, String schoolId, String startDate, String endDate, String subjectsId, String studentName, String yearPart, String quarterNum, String lessonType, String type) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        Integer history = 0;
        if (quarterNow.getYearPart().equals(Integer.parseInt(yearPart)) && quarterNow.getNum().equals(Integer.parseInt(quarterNum))) {

        }else {
            history = 1;
        }

        IPage<StatementData> statementDataIPage =  orderDetailMapper.statementDataEnd(page,schoolId,subjectsId,studentName,yearPart,quarterNum,lessonType,history,startDate,endDate);

        for (StatementData statementData:statementDataIPage.getRecords()){
            if (statementData.getYearClassId() != null){
                statementData.setYearClassName(CommonUtil.getYearClassNameForId(statementData.getYearClassId()));
            }
            statementData.setAdvancePrice(statementData.getResiduePrice());
            statementData.setStudentName(studentMapper.getStudentName(statementData.getStudentId()));
        }

        return statementDataIPage;
    }


    public OrderDetail getAtorderDetailOne(String schoolId,String studentId,String subjectsId,Quarter quarter,Integer readingStatus,Integer lessonType){
        OrderDetail orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,readingStatus,lessonType,true);
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,4,lessonType,false);
        }
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,5,lessonType,false);
        }
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,6,lessonType,false);
        }
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,2,lessonType,false);
        }
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,3,lessonType,false);
        }
        if (orderDetail == null){
            orderDetail = this.getAtOrderDetail(schoolId,studentId,subjectsId,quarter,readingStatus,lessonType,false);
        }
        return orderDetail;
    }

    public OrderDetail getAtOrderDetail(String schoolId,String studentId,String subjectsId,Quarter quarter,Integer readingStatus,Integer lessonType,boolean residueCourseBigZero){
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        if (residueCourseBigZero){
            if (readingStatus == 1){
                //获取在读的，剩余课时要大于0的
                orderDetailQueryWrapper.gt("residue_course_count",0);
            }
        }
        orderDetailQueryWrapper.eq("reading_status",readingStatus);
        orderDetailQueryWrapper.eq("student_id",studentId);
        orderDetailQueryWrapper.eq("subjects_id",subjectsId);
        orderDetailQueryWrapper.eq("school_id",schoolId);
        orderDetailQueryWrapper.eq("year_part",quarter.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());
        orderDetailQueryWrapper.eq("lesson_type",lessonType);
        orderDetailQueryWrapper.ne("status",2);

        orderDetailQueryWrapper.last("limit 1");
        orderDetailQueryWrapper.orderByAsc("created_at");
        OrderDetail orderDetail = orderDetailMapper.selectOne(orderDetailQueryWrapper);
        return orderDetail;
    }

    /**
     * 获取有剩余金额的订单
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @param readingStatus
     * @return
     */
    public List<OrderDetail> getHasResiduePriceList(String schoolId,String studentId,String subjectsId,Quarter quarter,Integer readingStatus){
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("student_id",studentId);
        orderDetailQueryWrapper.eq("subjects_id",subjectsId);
        orderDetailQueryWrapper.eq("school_id",schoolId);
        orderDetailQueryWrapper.eq("year_part",quarter.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());
        orderDetailQueryWrapper.ne("status",2);
        orderDetailQueryWrapper.gt("residue_price",0);//大于零的
        orderDetailQueryWrapper.gt("residue_course_count",0);
        orderDetailQueryWrapper.orderByAsc("residue_price");
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);
        return orderDetailList;
    }


    /**
     * 获取有剩余课时的数据
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @param
     * @return
     */
    public List<OrderDetail> getHasResidueHouseList(String schoolId,String studentId,String subjectsId,Quarter quarter,String orderBy){
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("student_id",studentId);
        orderDetailQueryWrapper.eq("subjects_id",subjectsId);
        orderDetailQueryWrapper.eq("school_id",schoolId);
        orderDetailQueryWrapper.eq("year_part",quarter.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());
        orderDetailQueryWrapper.ne("status",2);
        orderDetailQueryWrapper.gt("residue_course_count",0);//大于零的
        if (orderBy.equals("asc")){
            orderDetailQueryWrapper.orderByAsc("id");
        }else {
            orderDetailQueryWrapper.orderByDesc("id");
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);
        return orderDetailList;
    }

    /**
     *获取所扣金额大于一节课的钱的数据
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @param buckleClassMoney 一节课多少钱
     * @return
     */
    public List<RecordCourse> getBigBuckleClassHouseList(String schoolId,String studentId,String subjectsId,Quarter quarter,BigDecimal buckleClassMoney){
        //获取扣课时小于应扣金额的数据
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id",schoolId);
        recordCourseQueryWrapper.eq("student_id",studentId);
        recordCourseQueryWrapper.eq("subjects_id",subjectsId);
        recordCourseQueryWrapper.eq("quarter",quarter.getNum());
        recordCourseQueryWrapper.eq("year_part",quarter.getYearPart());
        recordCourseQueryWrapper.eq("buckle_class_house",3);//三个课时的
        recordCourseQueryWrapper.eq("is_deduct_house",1);
        recordCourseQueryWrapper.gt("buckle_class_money",buckleClassMoney);
        recordCourseQueryWrapper.orderByAsc("buckle_class_money");
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        return recordCourseList;
    }

    /**
     *获取所扣金额小于一节课的钱的数据
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @param buckleClassMoney 一节课多少钱
     * @return
     */
    public List<RecordCourse> getLessBuckleClassHouseList(String schoolId,String studentId,String subjectsId,Quarter quarter,BigDecimal buckleClassMoney){
        //获取扣课时小于应扣金额的数据
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id",schoolId);
        recordCourseQueryWrapper.eq("student_id",studentId);
        recordCourseQueryWrapper.eq("subjects_id",subjectsId);
        recordCourseQueryWrapper.eq("quarter",quarter.getNum());
        recordCourseQueryWrapper.eq("year_part",quarter.getYearPart());
        recordCourseQueryWrapper.eq("buckle_class_house",3);//三个课时的
        recordCourseQueryWrapper.eq("is_deduct_house",1);
        recordCourseQueryWrapper.lt("buckle_class_money",buckleClassMoney);
        recordCourseQueryWrapper.orderByAsc("buckle_class_money");
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        return recordCourseList;
    }

    /**
     * 获取已扣金额的数据
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @return
     */
    public List<RecordCourse> getDeductList(String schoolId,String studentId,String subjectsId,Quarter quarter){
        //获取扣课时小于应扣金额的数据
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id",schoolId);
        recordCourseQueryWrapper.eq("student_id",studentId);
        recordCourseQueryWrapper.eq("subjects_id",subjectsId);
        recordCourseQueryWrapper.eq("quarter",quarter.getNum());
        recordCourseQueryWrapper.eq("year_part",quarter.getYearPart());
        recordCourseQueryWrapper.eq("buckle_class_house",3);//三个课时的
        recordCourseQueryWrapper.eq("is_deduct_house",1);
        recordCourseQueryWrapper.orderByAsc("buckle_class_money");
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        return recordCourseList;
    }

    /**
     * 添加金额
     * @param orderDetail
     * @param orderDetailOld
     * @param recordCourseDiffPrice
     * @return
     */
    public boolean addApplyPrice(OrderDetail orderDetail,OrderDetail orderDetailOld,BigDecimal recordCourseDiffPrice,Boolean isAddUsePrice){

        Long orderId = 0L;
        if (orderDetailOld!=null){
            orderDetailOld.setPrice(orderDetailOld.getPrice().add(recordCourseDiffPrice));
            orderDetailOld.setSolidPrice(orderDetailOld.getSolidPrice().add(recordCourseDiffPrice));
            if (isAddUsePrice) {
                orderDetailOld.setUsePrice(orderDetailOld.getUsePrice().add(recordCourseDiffPrice));
            }
            orderDetailMapper.updateById(orderDetailOld);
            orderId = orderDetailOld.getOrderId();
        }else {
            orderDetail.setPrice(orderDetail.getPrice().add(recordCourseDiffPrice));
            orderDetail.setSolidPrice(orderDetail.getSolidPrice().add(recordCourseDiffPrice));
            if (isAddUsePrice){
                orderDetail.setUsePrice(orderDetail.getUsePrice().add(recordCourseDiffPrice));
            }
            orderDetailMapper.updateById(orderDetail);
            orderId = orderDetail.getOrderId();
        }
        OrderApply orderApply = orderApplyMapper.selectById(orderId);
        if (orderApply !=null){
            orderApply.setPrice(orderApply.getPrice().add(recordCourseDiffPrice));
            if (orderApply.getSolidPrice().compareTo(BigDecimal.ZERO)>0){
                orderApply.setSolidPrice(orderApply.getSolidPrice().add(recordCourseDiffPrice));
            }
            orderApplyMapper.updateById(orderApply);
        }
        return true;
    }

    /**
     * 减少金额
     * @param orderDetail
     * @param orderDetailOld
     * @param recordCourseDiffPrice
     * @return
     */
    public boolean subApplyPrice(OrderDetail orderDetail,OrderDetail orderDetailOld,BigDecimal recordCourseDiffPrice,Boolean isSubUsePrice){
        Long orderId = 0L;
        if (orderDetailOld!=null){
            orderDetailOld.setPrice(orderDetailOld.getPrice().subtract(recordCourseDiffPrice));
            orderDetailOld.setSolidPrice(orderDetailOld.getSolidPrice().subtract(recordCourseDiffPrice));
            if (isSubUsePrice){
                orderDetailOld.setUsePrice(orderDetailOld.getUsePrice().subtract(recordCourseDiffPrice));
            }
            orderDetailMapper.updateById(orderDetailOld);
            orderId = orderDetailOld.getOrderId();
        }else {
            orderDetail.setPrice(orderDetail.getPrice().subtract(recordCourseDiffPrice));
            orderDetail.setSolidPrice(orderDetail.getSolidPrice().subtract(recordCourseDiffPrice));
            if (isSubUsePrice){
                orderDetail.setUsePrice(orderDetail.getUsePrice().subtract(recordCourseDiffPrice));
            }
            orderDetailMapper.updateById(orderDetail);
            orderId = orderDetail.getOrderId();
        }

        OrderApply orderApply = orderApplyMapper.selectById(orderId);
        if (orderApply !=null){
            orderApply.setPrice(orderApply.getPrice().subtract(recordCourseDiffPrice));
            if (orderApply.getSolidPrice().compareTo(BigDecimal.ZERO)>0){
                orderApply.setSolidPrice(orderApply.getSolidPrice().subtract(recordCourseDiffPrice));
            }
            orderApplyMapper.updateById(orderApply);
        }
        return true;
    }

    /**
     *
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param quarter
     * @param houseClassMoney 一课次多少钱
     * @return
     */
    public BigDecimal addOrderDetailPrice(String schoolId,String studentId,String subjectsId,Quarter quarter,BigDecimal buckleMoney,BigDecimal houseClassMoney){
        List<OrderDetail> orderDetailList = this.getHasResidueHouseList(schoolId,studentId,subjectsId,quarter,"asc");
        BigDecimal diffPrice = buckleMoney;//差额
        if (orderDetailList.size()>0){
            for (OrderDetail orderDetail:orderDetailList){
                if (diffPrice.compareTo(BigDecimal.ZERO) == 0){
                    continue;
                }
                Integer residueCourseCount = orderDetail.getResidueCourseCount();
                //本次扣多少个课时
                BigDecimal stuDeductHour =   new BigDecimal(3);
                //本次应加到多少金额
                BigDecimal shouldBuckleMoney = houseClassMoney.multiply(new BigDecimal(residueCourseCount/3));
                BigDecimal diffBuckleMoney = shouldBuckleMoney.subtract(orderDetail.getResiduePrice());//本次应可加多少金额
                System.out.println("diffBuckleMoney:"+orderDetail.getResiduePrice());
                //本次应加多少金额
                if (diffBuckleMoney.compareTo(diffPrice)>0){
                    diffBuckleMoney = diffPrice;
                }else if (diffBuckleMoney.compareTo(BigDecimal.ZERO)<0){
                    diffBuckleMoney = new BigDecimal(0);
                }
                if (diffBuckleMoney.compareTo(BigDecimal.ZERO) == 0){
                    continue;
                }
                orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(diffBuckleMoney));
                orderDetail.setPrice(orderDetail.getPrice().add(diffBuckleMoney));
                orderDetail.setSolidPrice(orderDetail.getSolidPrice().add(diffBuckleMoney));
                orderDetailMapper.updateById(orderDetail);
                OrderApply orderApply = orderApplyMapper.selectById(orderDetail.getOrderId());
                if (orderApply != null){
                    orderApply.setPrice(orderApply.getPrice().add(diffBuckleMoney));
                    if (orderApply.getSolidPrice().compareTo(BigDecimal.ZERO)>0){
                        orderApply.setSolidPrice(orderApply.getSolidPrice().add(diffBuckleMoney));
                    }
                    orderApplyMapper.updateById(orderApply);
                }

                diffPrice = diffPrice.subtract(diffBuckleMoney);
            }
        }
        return diffPrice;
    }

}
